package com.design.pattern.strategy.factory;

import com.design.pattern.strategy.StrategyPatternService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author @追风少年
 * @description factory
 * @date 2022/4/23
 */
@Component
public class StrategyPatternFactory implements ApplicationContextAware {

    /**
     * 根据ActionName将具体的Action存放到Map中
     */
    private final Map<String,StrategyPatternService> strategyPatternMap = new HashMap<>();

    public StrategyPatternService getStrategyService(String actionName){
        return strategyPatternMap.get(actionName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, StrategyPatternService> strategyServiceMap =
                applicationContext.getBeansOfType(StrategyPatternService.class);

        strategyServiceMap.values().forEach(strategyPatternService -> {
            strategyPatternMap.put(strategyPatternService.getActionName(), strategyPatternService);
        });
    }

}
